package com.zscat.mallplus.qsg.contrller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dianping.dzopen.apis.TuangouAPI;
import com.dianping.dzopen.entity.MeituanDeal;
import com.zscat.mallplus.annotation.SysLog;
import com.zscat.mallplus.qsg.QsgDevice;
import com.zscat.mallplus.qsg.QsgMeal;
import com.zscat.mallplus.qsg.QsgStore;
import com.zscat.mallplus.qsg.service.IDeviceService;
import com.zscat.mallplus.qsg.service.IMealService;
import com.zscat.mallplus.qsg.service.IQsgStoreService;
import com.zscat.mallplus.sys.entity.SysUser;
import com.zscat.mallplus.util.DateUtil;
import com.zscat.mallplus.util.UserUtils;
import com.zscat.mallplus.utils.CommonResult;
import com.zscat.mallplus.utils.ValidatorUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.mozilla.javascript.ast.ArrayComprehensionLoop;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@Api(tags = "DeviceController", description = "设备套餐管理管理")
@RequestMapping("/qsg/devicemeal")
public class DeviceMealController {

    @Resource
    private IMealService mealService;
    @Resource
    private IDeviceService deviceService;
    @Resource
    private IQsgStoreService storeService;

    @GetMapping(value = "/getmeituandeal")
    public Object getmeituandeal() {
        SysUser user = UserUtils.getCurrentMember();
        QsgStore store = storeService.getById(user.getQsgStoreId());
        try {
            List<MeituanDeal> deals = new TuangouAPI().dealQueryShopDealArray(store.getMeituanAppid(),store.getMeituanAppsecret(),store.getOpenShopUuid(),store.getMeituanSession());
            return new CommonResult().success(deals);
        } catch (Exception e) {
            log.error("查询美团套餐：%s", e.getMessage(), e);
        }
        return new CommonResult().failed();
    }

    @SysLog(MODULE = "qsg", REMARK = "根据条件查询所有设备套餐管理列表")
    @ApiOperation("根据条件查询所有设备套餐管理列表")
    @GetMapping(value = "/list")
    public Object getDeviceByPage(@RequestParam(required = false) String mealName,
                                  @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                  @RequestParam(value = "pageSize", defaultValue = "50") Integer pageSize
    ) {
//        pageSize = 50;
        QueryWrapper qw = new QueryWrapper();
        qw.orderByDesc("create_datetime");
        qw.eq("store_id", UserUtils.getCurrentMember().getQsgStoreId());
        if (StringUtils.isNotBlank(mealName)){
            qw.eq("meal_name",mealName);
        }
        try {
            IPage<QsgMeal> meals = mealService.page(new Page<>(pageNum,pageSize),qw);
            return new CommonResult().success(meals);
        } catch (Exception e) {
            log.error("根据条件查询所有设备套餐管理列表：%s", e.getMessage(), e);
        }
        return new CommonResult().failed();
    }

    @SysLog(MODULE = "qsg", REMARK = "根据条件查询对应设备下的设备套餐列表")
    @ApiOperation("根据条件查询对应设备下的设备套餐列表")
    @GetMapping(value = "/listByDevice")
    public Object getDeviceByPage(String deviceId) {
        try {
            List<QsgMeal> meals = new ArrayList<>();
            QsgDevice device = deviceService.getById(deviceId);
            String mealId = device.getMealId();
            if (StringUtils.isBlank(mealId)){
                return new CommonResult().success(meals);
            }else {
                String[] mealIds = StringUtils.split(mealId,",");
                for (String id : mealIds){
                    QsgMeal meal = mealService.getById(id);
                    if (null!=meal){
                        meals.add(meal);
                    }
                }
                return new CommonResult().success(meals);
            }
        } catch (Exception e) {
            log.error("根据条件查询所有设备套餐管理列表：%s", e.getMessage(), e);
        }
        return new CommonResult().failed();
    }

    @SysLog(MODULE = "qsg", REMARK = "保存设备套餐表")
    @ApiOperation("保存设备套餐表")
    @PostMapping(value = "/create")
    public Object saveDevice(@RequestBody QsgMeal entity) {
        try {
            entity.setCreateDatetime(new Date());
            if (StringUtils.isNotBlank(entity.getStartTime())){
                entity.setStartTime(entity.getStartTime());
            }
            if (StringUtils.isNotBlank(entity.getEndTime())){
                entity.setEndTime(entity.getEndTime());
            }
            if (null!=entity.getPrice()){
                entity.setIntegral(entity.getPrice().multiply(new BigDecimal(100)).intValue());
            }
            entity.setStoreId(UserUtils.getCurrentMember().getQsgStoreId().intValue());
            if (mealService.save(entity)) {
                return new CommonResult().success();
            }
        } catch (Exception e) {
            log.error("保存设备套餐表：%s", e.getMessage(), e);
            return new CommonResult().failed();
        }
        return new CommonResult().failed();
    }

    @SysLog(MODULE = "qsg", REMARK = "更新设备套餐表")
    @ApiOperation("更新设备套餐表")
    @PostMapping(value = "/update/{id}")
    public Object updateDevice(@RequestBody QsgMeal entity) {
        try {
            if (StringUtils.isNotBlank(entity.getStartTime())){
                entity.setStartTime(entity.getStartTime());
            }
            if (StringUtils.isNotBlank(entity.getEndTime())){
                entity.setEndTime(entity.getEndTime());
            }
            if (null!=entity.getPrice()){
                entity.setIntegral(entity.getPrice().multiply(new BigDecimal(100)).intValue());
            }
            if (mealService.updateById(entity)) {
                return new CommonResult().success();
            }
        } catch (Exception e) {
            log.error("更新设备套餐表：%s", e.getMessage(), e);
            return new CommonResult().failed();
        }
        return new CommonResult().failed();
    }

    @SysLog(MODULE = "qsg", REMARK = "删除设备套餐表")
    @ApiOperation("删除设备套餐表")
    @GetMapping(value = "/delete/{id}")
    public Object deleteDevice(@ApiParam("设备套餐表id") @PathVariable Long id) {
        try {
            if (ValidatorUtils.empty(id)) {
                return new CommonResult().paramFailed("设备套餐表id");
            }
            if (mealService.removeById(id)) {
                //删除掉mealId
                return new CommonResult().success();
            }
        } catch (Exception e) {
            log.error("删除设备套餐表：%s", e.getMessage(), e);
            return new CommonResult().failed();
        }
        return new CommonResult().failed();
    }

    @SysLog(MODULE = "qsg", REMARK = "给设备套餐表分配设备套餐表")
    @ApiOperation("查询设备套餐表明细")
    @GetMapping(value = "/{id}")
    public Object getDeviceById(@ApiParam("设备套餐表id") @PathVariable Long id) {
        try {
            if (ValidatorUtils.empty(id)) {
                return new CommonResult().paramFailed("设备套餐表id");
            }
            QsgMeal meal = mealService.getById(id);
            return new CommonResult().success(meal);
        } catch (Exception e) {
            log.error("查询设备套餐表明细：%s", e.getMessage(), e);
            return new CommonResult().failed();
        }
    }
}
